package com.songshuai.webapi.baseapi.handler;

import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice(annotations = {RestController.class})
public class GlobalExceptionHandler {
    /**
     * 系统异常处理，比如：404,500
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public QueryResponse<?> defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {

        log.error("java webapi error", e);
        QueryResponse baseResp = new QueryResponse();
        baseResp.setMessage(e.getMessage());
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            baseResp.setCode(ResultStatus.HTTP_STATUS_NOT_FOUND.getErrorCode());
        }
        else if(e instanceof BusinessException){
            BusinessException businessException=(BusinessException)e;
            if(businessException!=null){
                baseResp.setCode(businessException.getCode());
            }
        }
        else {
            baseResp.setCode(ResultStatus.HTTP_STATUS_INTERNAL_SERVER_ERROR.getErrorCode());
        }
        baseResp.setData("");
        return baseResp;
    }
}
